package com.gao.alg.geek;

import java.util.HashMap;
import java.util.Map;

public class LRUCache2 {

    private Map<Integer,Node> cache;

    class Node{
        int value;
        int key;
        Node pre;
        Node next;
    }

    Node head;
    Node tail;
    int capacity;
    int size;
    public LRUCache2(int capacity){
        this.capacity = capacity;
        cache = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    public Integer get(int key){
        Node node = cache.get(key);
        if (node == null){
            return -1;
        }
        move2Head(node);
        return node.value;
    }

    public void put(int key,int value){
        Node node = cache.get(key);
        if (node == null){
            node = new Node();
            node.key = key;
            node.value = value;
            add2Head(node);
            cache.put(key,node);
            size++;
            if (size > capacity){
                size --;
                Node last = removeTail();
                cache.remove(key);
            }
        }else {
            move2Head(node);
            node.value = value;
        }
    }

    private Node removeTail() {
        Node last = tail.pre;
        removeNode(last);
        return last;
    }

    private void move2Head(Node node) {
        if (head.next.key == node.key){
           return;
        }
        removeNode(node);
        add2Head(node);
    }

    private void add2Head(Node node) {
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
        node.pre = head;
    }

    private void removeNode(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }


}
